




struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

ListNode* reverseKGroup(ListNode* head, int k) {

    // 计算链表长度
    int len = 0;
    ListNode* dummy = new ListNode(-1);
    dummy->next = head;
    ListNode* p = head;
    while(p){
        len++;
        p = p->next;
    }
    
    // 开始 K 个一组反转
    ListNode* pre = dummy;
    ListNode* cur = pre->next;
    ListNode* next;
    while(len && len >= k){
        for(int i=0;i<k-1;i++){
            next = cur->next;
            cur->next = next->next;
            next->next = pre->next;
            pre->next = next;
        }
        pre = cur;
        cur = pre->next;
        len -= k;
    }

    return dummy->next;
}